package cn.iocoder.yudao.module.signature.config;

import cn.iocoder.yudao.module.member.api.siteconfig.SiteConfigurationApi;
import cn.iocoder.yudao.module.member.api.siteconfig.dto.SiteConfigurationDto;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author liujq
 * @date 20250414 6:28
 */
@Configuration
@Slf4j
public class SignTaskExecutorConfiguration {

    private ThreadPoolTaskExecutor executor;

    @Resource
    @Lazy
    private SiteConfigurationApi siteConfigurationApi;

    @Bean("signTaskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(getCorePoolSize());
        executor.setMaxPoolSize(1000);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("sign-thread-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        log.info("初始化签名线程池: corePoolSize={}", executor.getCorePoolSize());
        executor.initialize(); // 显式初始化
        return executor;
    }

    private int getCorePoolSize() {
        SiteConfigurationDto config = siteConfigurationApi.getConfig();
        log.info("获取签名线程池配置: {}", JSON.toJSONString(config));
        if(config == null || config.getNumberLimit() == null) {
            return 1;
        }
        return config.getNumberLimit();
    }

    @PreDestroy
    public void destroy() {
        if (executor != null) {
            executor.shutdown();
            log.info("签名线程池已关闭");
        }
    }

}
